//
//  YMTableViewCell.m
//  WFCoretext
//
//  Created by 阿虎 on 14/10/28.
//  Copyright (c) 2014年 tigerwf. All rights reserved.
// 2 3 2 2 2 3 1 3 2 1

#import "YMTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "ContantHead.h"
#import "YMTapGestureRecongnizer.h"

#define kImageTag 9999


@implementation YMTableViewCell
{
    YMTextData *tempDate;
    UILabel * lineUp;
    UILabel * lineDown;
    UIImageView *timeImage;
    UIImageView *arrow;
    NSMutableArray *lineArry ;
}

-(void)didHeadPicAndNamePress{
	if ([self.delegate respondsToSelector:NSSelectorFromString(@"didPromulgatorNameOrHeadPicPressedForIndex:name:")]){
		[self.delegate didPromulgatorNameOrHeadPicPressedForIndex:self.stamp name:self.nameLbl.text];
	}
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        lineArry =[[NSMutableArray alloc]init];
        _hideReply = NO;
        
        // Initialization code
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        _headerImage = [[UIImageView alloc] initWithFrame:CGRectMake(offHead_X, 8, 50, TableHeader)];
        _headerImage.layer.cornerRadius = _headerImage.frame.size.width/2;
        _headerImage.layer.borderColor = RGB(27, 133, 203, 1).CGColor;
        _headerImage.layer.borderWidth=2;
        _headerImage.layer.masksToBounds=YES;
        [_headerImage setImage:[UIImage imageNamed:@"日期"]];
        //自定义头像箭头
        UIImageView *borderImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"日期"]];
        borderImage.frame = CGRectMake( -2, -2, 70, 70);
//        [self.contentView addSubview:borderImage];
        
        _headerImage.backgroundColor = [UIColor clearColor];
		_headerImage.userInteractionEnabled = YES;
		UIGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHeadPicAndNamePress)];
		[_headerImage addGestureRecognizer:tap1];
        
        [self.contentView addSubview:_headerImage];
        
		_nameLbl = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_headerImage.frame)+8, CGRectGetMidY(_headerImage.frame)-12.5, screenWidth - 120, TableHeader/2)];
        _nameLbl.textAlignment = NSTextAlignmentLeft;
        _nameLbl.font = [UIFont systemFontOfSize:15.0];
        _nameLbl.textColor = RGB(27, 133, 203, 1);
		_nameLbl.userInteractionEnabled = YES;
		UIGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHeadPicAndNamePress)];
		[_nameLbl addGestureRecognizer:tap2];
        [self.contentView addSubview:_nameLbl];
        
        
        timeImage =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"时钟图标"]];
        _introLbl = [[UILabel alloc] initWithFrame:CGRectMake(20 + TableHeader + 20, 5 + TableHeader/2 , screenWidth - 120, TableHeader/2)];
        _introLbl.numberOfLines = 1;
        _introLbl.font = [UIFont systemFontOfSize:12.0];
        _introLbl.textColor = [UIColor grayColor];
        [self.contentView addSubview:_introLbl];
        [self.contentView addSubview:timeImage];
        
        _imageArray = [[NSMutableArray alloc] init];
        _ymTextArray = [[NSMutableArray alloc] init];
        _ymShuoshuoArray = [[NSMutableArray alloc] init];
        
        _foldBtn = [UIButton buttonWithType:0];
        [_foldBtn setTitle:@"Full Text" forState:0];
        _foldBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
        _foldBtn.backgroundColor = [UIColor clearColor];
        _foldBtn.titleLabel.font = [UIFont systemFontOfSize:10.0];
        [_foldBtn setTitleColor:RGB(27, 133, 203, 1) forState:0];
        [_foldBtn addTarget:self action:@selector(foldText) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_foldBtn];
        
        _replyImageView = [[UIImageView alloc] init];
        
        _replyImageView.backgroundColor = RGB(35, 35, 35, 1);
        _replyImageView.layer.cornerRadius=5;
        _headerImage.layer.masksToBounds=YES;
//        [_replyImageView setImage:[UIImage imageNamed:@"留言上部"]];
        arrow=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow"]];
        [self.contentView addSubview:_replyImageView];
        [self.contentView addSubview:arrow];
        
        _replyBtn = [YMButton buttonWithType:0];
        [_replyBtn setImage:[UIImage imageNamed:@"回复按钮.png"] forState:0];
//        [_replyBtn setBackgroundImage:[UIImage imageNamed:@"回复按钮.png"] forState:UIControlStateNormal];
        [self.contentView addSubview:_replyBtn];
        lineUp =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMidX(_headerImage.frame),0 , 1, CGRectGetMinY(_headerImage.frame)-5)];
        lineDown = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMidX(_headerImage.frame),CGRectGetMaxY(_headerImage.frame)+5 , 1, CGRectGetMaxY(_replyImageView.frame)-CGRectGetMaxY(_headerImage.frame)+15)];
        [lineUp setBackgroundColor:RGB(26, 87, 126, 1)];
        [lineDown setBackgroundColor:RGB(26, 87, 126, 1)];
        [self.contentView addSubview:lineUp];
        [self.contentView addSubview:lineDown];
//        self.backgroundColor = [UIColor whiteColor];
        
        _deleteBtn =[UIButton buttonWithType:UIButtonTypeSystem];
        [_deleteBtn setTitle:NSLocalizedString(@"Delete", nil)  forState:UIControlStateNormal];
        [_deleteBtn.titleLabel setFont:[UIFont systemFontOfSize:10]];
        [_deleteBtn addTarget:self action:@selector(clickDelete) forControlEvents:UIControlEventTouchUpInside];
        [_deleteBtn setTitleColor:RGB(27, 133, 203, 1) forState:UIControlStateNormal];
        _deleteBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
        [self.contentView addSubview:_deleteBtn];

        
    }
    return self;
}

- (void)foldText{
    
    if (tempDate.foldOrNot == YES) {
        tempDate.foldOrNot = NO;
        [_foldBtn setTitle:@"Collapse" forState:0];
    }else{
        tempDate.foldOrNot = YES;
        [_foldBtn setTitle:@"Full Text" forState:0];
    }
    
    [_delegate changeFoldState:tempDate onCellRow:self.stamp];
    
}

- (void)clickDelete{
    if ([self.delegate respondsToSelector:NSSelectorFromString(@"didDeletelCellIndex:")]) {
        [self.delegate didDeletelCellIndex:self.deleteBtn];
    }
    
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}


- (void)setYMViewWith:(YMTextData *)ymData{
    
    // NSLog(@"width = %f",screenWidth);
    
    tempDate = ymData;
    
    for ( int i = 0; i < _ymShuoshuoArray.count; i ++) {
        WFTextView * imageV = (WFTextView *)[_ymShuoshuoArray objectAtIndex:i];
        if (imageV.superview) {
            [imageV removeFromSuperview];
            
        }
    }
	
	//处理说说内容
    [_ymShuoshuoArray removeAllObjects];
    WFTextView *textView = [[WFTextView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_headerImage.frame) + 8, CGRectGetMaxY(_nameLbl.frame)+10  , screenWidth - offSet_X - CGRectGetMaxX(_headerImage.frame), 0)];
    textView.backgroundColor =RGB(35, 35, 35, 0);
    textView.delegate = self;
    textView.attributedData = ymData.attributedDataWF;
    textView.isFold = ymData.foldOrNot;
    textView.isDraw = YES;
	textView.type = TextTypeContent;
    [textView setOldString:ymData.showShuoShuo andNewString:ymData.completionShuoshuo];
    [self.contentView addSubview:textView];
    
    BOOL foldOrnot = ymData.foldOrNot;
    float hhhh = foldOrnot?ymData.shuoshuoHeight:ymData.unFoldShuoHeight;
    
    textView.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame) + 8, CGRectGetMaxY(_nameLbl.frame)+8 , screenWidth - offSet_X - CGRectGetMaxX(_headerImage.frame), hhhh);
    NSLog(@"------>>%f",SCREEN_WIDTH-CGRectGetMaxX(textView.frame));
    [_ymShuoshuoArray addObject:textView];
    
    //按钮
    _foldBtn.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame) +8, CGRectGetMaxY(_nameLbl.frame)+8+ hhhh  , 100, 12 );
    
    if (ymData.islessLimit) {
        
        _foldBtn.hidden = YES;
    }else{
        _foldBtn.hidden = NO;
    }
    
    
    if (tempDate.foldOrNot == YES) {
        
        [_foldBtn setTitle:@"Full Text" forState:0];
    }else{
        
        [_foldBtn setTitle:@"Collapse" forState:0];
    }
    

    
    //图片部分
    for (int i = 0; i < [_imageArray count]; i++) {
        
        UIImageView * imageV = (UIImageView *)[_imageArray objectAtIndex:i];
        if (imageV.superview) {
            [imageV removeFromSuperview];
            
        }
        
    }
    
    [_imageArray removeAllObjects];
    
    for (int  i = 0; i < [ymData.showImageArray count]; i++) {
        float  x =CGRectGetMaxX(_headerImage.frame)+8; //头像的最大距离
        float between=(screenWidth - 3*80-x)/4;     //间隔距离
        
        
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(between*(i%3 + 1) + 80*(i%3)+x-between,10 * ((i/3)+1) + (i/3) *  ShowImage_H + hhhh + kDistance + (ymData.islessLimit?0:30), 80, ShowImage_H)];
        image.userInteractionEnabled = YES;
        CGRect allImageFrame=CGRectMake(x,CGRectGetMaxY(_nameLbl.frame)+10+hhhh+kDistance, SCREEN_WIDTH-x-12, SCREEN_HEIGHT-x-12);
//      计算九宫格坐标
        image.frame=[self calculateNinePalaceFrameAndSuperViewFrame:allImageFrame forNumber:i];
//        image.contentMode =UIViewContentModeScaleAspectFit;
        YMTapGestureRecongnizer *tap = [[YMTapGestureRecongnizer alloc] initWithTarget:self action:@selector(tapImageView:)];
        [image addGestureRecognizer:tap];
        tap.appendArray = ymData.showImageArray;
        image.backgroundColor = [UIColor clearColor];
        image.tag = kImageTag + i;
//		这句话 让图片 支持网络异步加载图片
        if (ymData.localDataNoUpload) {
            [image setImage:[ymData.smallImageArray objectAtIndex:i]];
        }else{
            [image sd_setImageWithURL:[NSURL URLWithString:[ymData.smallImageArray objectAtIndex:i]] placeholderImage:[UIImage imageNamed:@"nilPic.png"]];
        }
        NSLog(@"---->%@",[ymData.smallImageArray objectAtIndex:i]);
//        image.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",[ymData.showImageArray objectAtIndex:i]]];
        [self.contentView addSubview:image];
        [_imageArray addObject:image];
        
    }

    
   
    if (_hideReply) {
        [_replyBtn removeFromSuperview];
        
    }else{
        
        //最下方回复部分
        for (int i = 0; i < [_ymTextArray count]; i++) {
            
            WFTextView * ymTextView = (WFTextView *)[_ymTextArray objectAtIndex:i];
            if (ymTextView.superview) {
                [ymTextView removeFromSuperview];
                //  NSLog(@"here");
                
            }
            
        }
        
        [_ymTextArray removeAllObjects];
        for (UILabel * lie in  lineArry) {
            [lie removeFromSuperview];
            
        }
        [lineArry removeAllObjects];
        
        float origin_Y = 10;
        NSUInteger scale_Y = ymData.showImageArray.count - 1;
        float balanceHeight = 0; //纯粹为了解决没图片高度的问题
        if (ymData.showImageArray.count == 0) {
            scale_Y = 0;
            balanceHeight = - ShowImage_H;
        }
        
        float backView_Y = 0;
        float backView_H = 0;
        
        for (int i = 0; i < ymData.replyDataSource.count; i ++ ) {
            //评论下方划线
            UILabel *line=[[UILabel alloc]init];
            [line setBackgroundColor:RGB(69, 69, 69, 69)];
            
            //评论
            WFTextView *_ilcoreText = [[WFTextView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_headerImage.frame)+8,10 + ShowImage_H + (ShowImage_H + 10)*(scale_Y/3) + origin_Y + hhhh + kDistance + (ymData.islessLimit?0:30) + balanceHeight + kReplyBtnDistance, screenWidth - offSet_X -CGRectGetMaxX(_headerImage.frame), 0)];
            
            if (i == 0) {
                backView_Y = CGRectGetMaxY(_nameLbl.frame)+10 + ShowImage_H + (ShowImage_H + 10)*(scale_Y/3) + origin_Y + hhhh + kDistance + (ymData.islessLimit?0:30);
            }
            
            _ilcoreText.delegate = self;
			
			_ilcoreText.type = TextTypeReply;
			_ilcoreText.replyIndex = i;
            if (ymData.attributedData.count!=0) {
                _ilcoreText.attributedData = [ymData.attributedData objectAtIndex:i];
            }
            
            if (ymData.completionReplySource.count !=0) {
                 [_ilcoreText setOldString:[ymData.replyDataSource objectAtIndex:i] andNewString:[ymData.completionReplySource objectAtIndex:i]];
            }
           
            
            _ilcoreText.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame)+8+8,CGRectGetMaxY(_nameLbl.frame)+10 + ShowImage_H + (ShowImage_H + 10)*(scale_Y/3) + origin_Y + hhhh + kDistance + (ymData.islessLimit?0:30) + balanceHeight + kReplyBtnDistance, screenWidth - offSet_X-CGRectGetMaxX(_headerImage.frame)-8-8, [_ilcoreText getTextHeight]);
             //设置评论下方划线的坐标
            line.frame = CGRectMake(CGRectGetMinX(_ilcoreText.frame), CGRectGetMaxY(_ilcoreText.frame)+2, CGRectGetWidth(_ilcoreText.frame), 0.5);
            [self.contentView addSubview:_ilcoreText];
            (i!=ymData.replyDataSource.count-1)? [self.contentView addSubview:line]:nil;
            origin_Y += [_ilcoreText getTextHeight] + 5 ;
            
            backView_H += _ilcoreText.frame.size.height;
            
            [_ymTextArray addObject:_ilcoreText];
            [lineArry addObject:line];
        }
        
        backView_H += (ymData.replyDataSource.count - 1)*5;
        
    
        if (ymData.replyDataSource.count == 0) {//没回复的时候
            
            _replyImageView.frame = CGRectMake(offSet_X, backView_Y - 10 + balanceHeight + 5 + kReplyBtnDistance, 0, 0);
            _replyBtn.frame = CGRectMake(screenWidth - offSet_X - 23 +10 , CGRectGetMaxY(_nameLbl.frame)+8 + hhhh+ kDistance + ShowImage_H+(ShowImage_H + 10)*(scale_Y/3) + origin_Y + (ymData.islessLimit?0:30) + balanceHeight+10 , 23, 23);
            
            lineDown.frame =CGRectMake(CGRectGetMidX(_headerImage.frame),CGRectGetMaxY(_headerImage.frame)+8 , 1,CGRectGetMaxY(_replyBtn.frame)-CGRectGetMaxY(_headerImage.frame)+8);
            arrow.frame=CGRectMake(0, 0, 0, 0);
            
        }else{
            
            _replyImageView.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame)+8, backView_Y - 10 + balanceHeight + 5 + kReplyBtnDistance, screenWidth - offSet_X -CGRectGetMaxX(_headerImage.frame), backView_H + 20 - 12);//微调
            _replyBtn.frame = CGRectMake(screenWidth - offSet_X - 23+10, _replyImageView.frame.origin.y - 30, 23,23);
            
            lineDown.frame = CGRectMake(CGRectGetMidX(_headerImage.frame),CGRectGetMaxY(_headerImage.frame)+8 , 1, CGRectGetMaxY(_replyImageView.frame)-CGRectGetMaxY(_headerImage.frame)+5);
            arrow.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame)+8+10+16, CGRectGetMinY(_replyImageView.frame)-6, 9, 6);
            
        }
//        根据文字内容获取size
        CGSize timeSize =[ymData.intro sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12.0]}];
        
        
        _introLbl.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame)+8+8+10, CGRectGetMinY(_replyBtn.frame), timeSize.width, CGRectGetHeight(_replyBtn.frame));
        _deleteBtn.frame= CGRectMake(CGRectGetMaxX(_introLbl.frame)+16, CGRectGetMinY(_introLbl.frame), CGRectGetMinX(_replyBtn.frame)-CGRectGetMaxX(_introLbl.frame)-16, CGRectGetHeight(_replyBtn.frame));
        timeImage.frame = CGRectMake(CGRectGetMaxX(_headerImage.frame)+8, CGRectGetMidY(_introLbl.frame)-5, 10, 10);
        
            
    }
    
    
}

#pragma mark - ilcoreTextDelegate
//- (void)clickMyself:(NSString *)clickString{
//    
//    //延迟调用下  可去掉 下同
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC));
//    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:clickString message:nil delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
//        [alert show];
//        
//        
//    });
//}

- (void)clickWFCoretext:(NSString *)clickString{
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    
		if ([self.delegate respondsToSelector:NSSelectorFromString(@"didRichTextPress:index:")]) {
			[self.delegate didRichTextPress:clickString index:self.stamp];
		}
    });
}

-(void)clickWFCoretext:(NSString *)clickString replyIndex:(NSInteger)index{
	dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC));
	dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
		
		if ([self.delegate respondsToSelector:NSSelectorFromString(@"didRichTextPress:index:replyIndex:")]) {
			[self.delegate didRichTextPress:clickString index:self.stamp replyIndex:index];
		}
	});
}

#pragma mark - 点击照片
- (void)tapImageView:(YMTapGestureRecongnizer *)tapGes{
    
    [_delegate showImageViewWithImageViews:tapGes.appendArray byClickWhich:tapGes.view.tag];
    
}

-(YMTextData*)getYMTextData{
    return tempDate;
}

//计算九宫格坐标
-(CGRect)calculateNinePalaceFrameAndSuperViewFrame:(CGRect)SuperViewFrame forNumber:(int)i
{
    float x,y,w,h; CGRect frame;
    w = (SuperViewFrame.size.width-10)/3;
    h=w;
    x = SuperViewFrame.origin.x+(i%3)*(5+w);
    NSLog(@"-->>%i",i/4);
    y = SuperViewFrame.origin.y+(i/3)*(h+5);
    frame = CGRectMake(x, y, w, h);
    return frame;
}

@end
